<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if (config('common.sql_log.is_write')) {
            $this->writeSqlLog();
        }
    }

    /**
     * FunctionName：writeSqlLog
     * Description：将 sql 语句 写入 log
     * Author：lwl
     */
    private function writeSqlLog()
    {
        DB::listen(
            function ($sql) {
                $sql = $sql->sql;
                $logInstance = Log::channel('query_log');
                $logInstance->info(PHP_EOL);
                $logInstance->info('---------------------------------------- 响应 START ------------------------------');
                $logInstance->info('请求唯一标识:' . uuid());
                $logInstance->info('请求地址:' . request()->getPathInfo());
                $logInstance->info('语句:' . $sql);
                $consuming = microtime(true) - LARAVEL_START;
                $memory = memory_get_peak_usage(true);
                $memoryMB = $memory / 1024 / 1024;
                $logInstance->info('语句耗时:' . $consuming . '秒');
                $configMemoryThreshold = config('common.sql_log.memory_threshold');
                if ($memoryMB >= $configMemoryThreshold) {
                    $logInstance->info('内存警告:内存已超过临界值,请优化代码,以免造成内存溢出');
                }

                if ($memoryMB < $configMemoryThreshold && abs($configMemoryThreshold - $memoryMB) <= 5) {
                    $logInstance->info('内存提示:内存将要达到临界值,请优化代码,以免造成内存溢出');
                }

                if ($consuming >= config('common.sql_log.time_out')) {
                    $logInstance->info('消耗提示:消耗时间过长,请优化代码,以免造成 TimeOut');
                }

                $logInstance->info('占用内存:' . $memory / 1024 / 1024 . 'MB');
                $logInstance->info('内存临界值:' . $configMemoryThreshold . 'MB');
                $logInstance->info('---------------------------------------- 响应 END ----------------------------------');
            }
        );
    }
}
